var UserGridPanel = function() {
	return {
		init : function() {
			var validator;
			var account_validator;
			var tableId = "user_grid_panel";
			util.initCheckBox(tableId);
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "keyWord",
					"value" : $("#id_keyword").val().trim()
				});
				aoData.push({
					"name" : "accounttype",
					"value" : $("#id_user_class").val()
				});
				aoData.push({
					"name" : "isBinded",
					"value" :$('#id_unbinded').is(':checked') ? '1':null
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
						$("#unBindedCount").text(resp.unbindedCount);
						$(".belong").each(function(){
							$(this).hover(function() {
								$(this).children("em").css('display','inline-block');
							}, function() {
								$(this).children("em").css('display','none');
							});
						});
					}
				});
			};
			
			var dt=$('#user_grid_panel').DataTable(
					{
						"processing" : true,
						"serverSide" : true,
						"sAjaxSource" : "main/sysUser/getUserByCusId.mvc",
						"fnServerData" : queryData,
						"pageLength" : 10,
						"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
						"oLanguage" : util.getDToLanguage(),
						"columns" : [
								{
									"data" : "pkId",
									"render" : function(data, type,
											full, meta) {
										return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
									},
									"bSortable" : false
								}, 
								{
									"data" : "loginName",
									"render" : function(data, type,
											full, meta) {
										//锁定
										if (full.isLock == '1') {
											return '<i class="icon-lock"></i>' +'&nbsp;&nbsp;'+ data;
										} else if (data) {
											//未锁定
											return '&nbsp;&nbsp;&nbsp;&nbsp;'+data;
										}
									},
									"defaultContent": "",
									"bSortable" : false
								}, {
									"data" : "empName",
									"bSortable" : false,
									"defaultContent": ""
								}, {
									"data" : "email",
									"bSortable" : false,
									"defaultContent": "",
									"sWidth":"220px",
								}, {
									"data" : "phone",
									"bSortable" : false,
									"defaultContent": ""
								}, {
									"data" : "typestr",
									"render" : function(data, type, full, meta) {
										if (data == '1') {
											return '电池pack厂账户';
										}else if(data == '2') {
											return '客户账户';
										}
									},
									"bSortable" : false,
									"defaultContent": ""
								}, {
									"data" : "facName",
									"bSortable" : false,
									"sClass" : "belong",
									"render" : function(data, type, full, meta) {
										if (full.address) {
											return '' + data + '<em style="display:none;">' + full.address + '</em>';
										}else {
											return data;
										}
									},
									"defaultContent": ""
								}, {
									"data" : "rnames",
									"bSortable" : false,
									"defaultContent": ""
								},{
									"data" : "accountStartDateStr",
									"bSortable" : false,
									"defaultContent": ""
								},{
									"data" : "accountEndDateStr",
									"bSortable" : false,
									"defaultContent": ""
								},{
									"data" : "cusId",
									"bSortable" : false,
									"visible" : false,
									"defaultContent": ""
								},{
									"data" : "parentCusId",
									"bSortable" : false,
									"visible" : false,
									"defaultContent": ""
								}],
							"fnDrawCallback" : function(oSetting) {
								util.clearSelected(tableId);
							}
					});
			
			//绑定账户
			$('#user_binding').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				} else if(d[0].pkId != null){
					util.showModal("#_alertModal", "请选择一条未绑定的记录进行操作！");
					return false;
				} else {
					var flag = checkCusAuthorization();
					if(flag == false){
						util.showModal("#_alertModal", "无法操作同级账户！");
						return false;
					}
					var u_id = d[0].pkId;
					var e_id = d[0].eId;
					$('#bind_account_title').text('绑定账号');
					//util.getDictByParentKey(null, 'form_role', '','main/sysUser/getRoleOptions.mvc');
					showBindInfo(u_id, e_id);
				}
			});
			
			//修改绑定
			$('#user_binding_edit').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				} else if (d[0].pkId == null) {
					util.showModal("#_alertModal", "请选择一条已绑定的记录进行操作！");
					return false;
				} else {
					var flag = checkCusAuthorization();
					if(flag == false){
						util.showModal("#_alertModal", "无法操作同级账户！");
						return false;
					}
					var u_id = d[0].pkId;
					var e_id = d[0].eId;
					$('#bind_account_title').text('编辑绑定');
					//util.getDictByParentKey(null, 'form_role', '','main/sysUser/getRoleOptions.mvc');
					showBindInfo(u_id, e_id);
				}
			});

			//账户期限设置
			$('#user_validity').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				debugger
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return false;
				} else if (d[0].pkId == null) {
					util.showModal("#_alertModal", "请选择一条已绑定的记录进行操作！");
					return false;
				} else {
					var flag = checkCusAuthorization();
					if(flag == false){
						util.showModal("#_alertModal", "无法操作同级账户！");
						return false;
					}
					var u_id = d[0].pkId;
					var e_id = d[0].eId;
					setUserInfo(e_id);
					//$('#bind_account_title').text('编辑绑定');
					$("#account_validity").modal({show:true,keyboard:false});
				}
			});

			$("#account_validity_type").change(function(e) {
				var date_str = $("#account_start_date").text();
				var startDate = new Date(Date.parse(date_str.replace(/-/g, "/")));
				debugger
				var type = $(this).children('option:selected').val(); 
				if(type == '0') {
					//账户期限永久
					$("#account_end_date").val("");
				}else if(type == '1') {
					//账户期限半年
					var endDate = startDate.addMonth(6);
					var endDateStr = endDate.format("yyyy-MM-dd hh:mm:ss");
					$("#account_end_date").val(endDateStr);
				}else if(type == '2') {
					//一年
					var endDate = startDate.addYear(1);
					var endDateStr = endDate.format("yyyy-MM-dd hh:mm:ss");
					$("#account_end_date").val(endDateStr);
				}else if(type == '3') {
					//两年
					var endDate = startDate.addYear(2);
					var endDateStr = endDate.format("yyyy-MM-dd hh:mm:ss");
					$("#account_end_date").val(endDateStr);
				}else if(type == '4') {
					//五年
					var endDate = startDate.addYear(5);
					var endDateStr = endDate.format("yyyy-MM-dd hh:mm:ss");
					$("#account_end_date").val(endDateStr);
				}else if(type == '5') {
					//十年
					var endDate = startDate.addYear(10);
					var endDateStr = endDate.format("yyyy-MM-dd hh:mm:ss");
					$("#account_end_date").val(endDateStr);
				}else if(type == '6') {
					$("#account_end_date").removeAttr("disabled");
				}
			});

			$("#account_validity_save").on("click",function(e){
				//debugger
				account_validator = validateAccountForm("account_validity_form");
				if(!account_validator.form()) {
					return false;
				}
				var d = {};
				var pkId = $("#account_validity_pkId").val();
				var userId = $("#account_validity_eId").val();
				var loginName = $("#account_login_name").text();
				var accountStartDate = $("#account_start_date").text();
				var accountEndDate = $("#account_end_date").val();
				var accountValidity = $("#account_validity_type").val();
				d['pkId'] = pkId;
				d['userId'] = userId;
				d['loginName'] = loginName;
				d['accountStartDateStr'] = accountStartDate;
				d['accountEndDateStr'] = accountEndDate;
				d['accountValidity'] = accountValidity;
				var table = $('#user_grid_panel').DataTable();
				var currentPage =table.page();
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/saveOrUpdateValidityInfo.mvc",
					"dataType" : "json",
					"data" : d,
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '保存成功！'});
							$("#account_validity_close").click();
							clearAccountValidityForm();
							table.page(currentPage).draw('page');
						} else if(resp.msg=='error') {
							rmsBox.notify('error', {msg: '数据异常！',delay:3000});
						} 
					}
				});

			});

			$("#account_validity_close").on("click",function(e){
				clearAccountValidityForm();
				if(account_validator) {
					$("#account_validity_form").validate().resetForm();
				}
			});

			function checkCusAuthorization(){
				var flag = true;
				var a = [];
				a = util.getCheckedData("user_grid_panel");
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/checkUserClass.mvc",
					"async": false,
					"dataType" : "json",
					"data" : ''
				}).complete(function(resp){
					//判断是否为客户账户
					debugger
					var data = JSON.parse(resp.responseText);
					if(data.flag == "true") {
						if(a[0].cusId == data.cusId){
							flag = false;
						}else {
							flag = true;
						}
					}else {
						flag = true;
					}
				});
				
				return flag;
				

			}

			function checkCusArrayAuthorization(){
				var flag = true;
				var a = [];
				a = util.getCheckedData("user_grid_panel");
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/checkUserClass.mvc",
					"async": false,
					"dataType" : "json",
					"data" : ''
				}).complete(function(resp){
					//判断是否为客户账户
					debugger
					var data = JSON.parse(resp.responseText);
					if(data.flag == "true") {
						for (var i=0;i<a.length;i++) {
							if(a[i].cusId == data.cusId) {
								flag = false;
							}
						}
					}else {
						flag = true;
					}
				});
				
				return flag;
				

			}

			function clearAccountValidityForm() {
				debugger
				$("#account_validity_form input").val('');
				$("#account_validity_form span.my-text").text('');
			}

			function setUserInfo(e_id) {
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/queryAccountValidityInfo.mvc",
					"dataType" : "json",
					"data" : {
						"eId" : e_id
					},
					"success" : function(resp) {
						debugger
						var data = resp.data;
						if(data){
							$("#account_validity_pkId").val(data.pkId);
							$("#account_validity_eId").val(data.eId);
							$("#account_login_name").text(data.loginName);
							if(data.accountStartDateStr!=null){
								$("#account_start_date").text(data.accountStartDateStr);
							}
							$("#account_end_date").val(data.accountEndDateStr);
							if(data.accountEndDateStr!=null&&data.accountEndDateStr!=''){
								//$("#account_end_date").datepicker({minDate:  }); 
							}
							if(data.accountValidity != '6'){
								$("#account_end_date").attr({"disabled":"disabled"});
							}
							$("#account_validity_type").val(data.accountValidity);
						}
					}
				});
				
			}


			
			//弹窗绑定窗口
			function showBindInfo(u_id, e_id) {
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/queryUserBind.mvc",
					"dataType" : "json",
					"data" : {
						"eId" : e_id
					},
					"success" : function(resp) {
						var data = resp.data;
						debugger
						if (data) {
							if(resp.flag){
								$("#role").show();
								$("#form_role").show();
								$("#form_role").text(resp.rname);
								$("#form_roleId").val(resp.roleId);
							}else {
								$("#role").hide();
								$("#form_role").hide();
								$("#form_role").text('');
								$("#form_roleId").val('');
							}
							$("#form_pkId").val(u_id);
							$("#form_eId").val(e_id);
							$("#form_userClass").val(data.accounttype);
							$("#form_ownerComp").text(data.ownerComp==null?'':data.ownerComp);
							$("#form_ownerFactory").text(data.facName);
							$("#prov_city").text(data.address);
							$("#form_empName").text(data.empName);
							$("#form_sex").text(data.sex);
							$("#form_email").text(data.email);
							$("#form_phone").text(data.phone);
							$("#form_job").text(data.job);
							$("#user_info_table span.my-text").each(function(){
								$(this).attr("title",$(this).text());
							});
							$("#form_user_loginName").val(data.loginName);
							$("#form_pass").val(data.pass);
							$("#form_oldPass").val(data.pass);
							if (data.isLock=='1') {
                                $("#form_isLock").parent().addClass("checked");
                            }
                            if (data.showMessage=='0') {
                                $("#form_isShowMessage").parent().addClass("checked");
                            }
							$("#bind_account").modal({show:true,keyboard:false});
						} else {
							util.showModal("#_alertModal", "数据异常！");
						}
					}
				});
			}
			
			//解除绑定
			$('#user_binding_cancel').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					var flag = checkCusArrayAuthorization();
					if(flag == false){
						util.showModal("#_alertModal", "无法操作同级账户！");
						return false;
					}
					for (var i=0;i<d.length;i++) {
						if (!d[i].pkId) {
							util.showModal("#_alertModal", "请选择已绑定的记录！");
							return;
						}
					}
					util.showModal("#_confirmModal", "您确定要解除选中记录的绑定？", "_bind_cancel_yes");
				}
			});
			
			//解除绑定
			$("#_confirmModal").on('click', '#_bind_cancel_yes', function() {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#user_grid_panel').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/cancelUserBind.mvc",
					"dataType" : "json",
					"data" : {
						"userId" : idArray.join(",")
					},
					"success" : function(resp) {
						rmsBox.notify('success', {msg: '解除绑定成功！'});
						table.draw(true);
					}
				});
			});
			
			//锁定账户
			$('#user_lock').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					var flag = checkCusArrayAuthorization();
					if(flag == false){
						util.showModal("#_alertModal", "无法操作同级账户！");
						return false;
					}
					for (var i=0;i<d.length;i++) {
						if (d[i].pkId==null) {
							util.showModal("#_alertModal", "请选择已绑定的记录！");
							return;
						}
						if (d[i].isLock == '1') {
							util.showModal("#_alertModal", "请选择未锁定的记录！");
							return;
						}
					}
					util.showModal("#_confirmModal", "您确定要锁定选中的记录？", "_user_lock_yes");
				}
			});
			
			//确认锁定
			$("#_confirmModal").on('click', '#_user_lock_yes', function() {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#user_grid_panel').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/lockUser.mvc",
					"dataType" : "json",
					"data" : {
						"userId" : idArray.join(",")
					},
					"success" : function(resp) {
						rmsBox.notify('success', {msg: '用户锁定成功！'});
						table.draw(true);
					}
				});
			});
			
			//取消锁定
			$('#user_lock_cancel').on('click', function(e) {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					var flag = checkCusArrayAuthorization();
					if(flag == false){
						util.showModal("#_alertModal", "无法操作同级账户！");
						return false;
					}
					for (var i=0;i<d.length;i++) {
						if (d[i].isLock != '1') {
							util.showModal("#_alertModal", "请选择已锁定的记录！");
							return;
						}
					}
					util.showModal("#_confirmModal", "您确定要解除选中记录的绑定？", "_lock_cancel_yes");
				}
			});
			
			//确认取消锁定
			$("#_confirmModal").on('click', '#_lock_cancel_yes', function() {
				var d = [];
				d = util.getCheckedData("user_grid_panel");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#user_grid_panel').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/lockCancel.mvc",
					"dataType" : "json",
					"data" : {
						"userId" : idArray.join(",")
					},
					"success" : function(resp) {
						rmsBox.notify('success', {msg: '用户解除锁定成功！'});
						table.draw(true);
					}
				});
			});
			
			//表单关闭按钮
			$("#form_btn_close").click(function(e) {
				clearForm();
				if(validator) {
					$("#user_form").validate().resetForm();
				}
			});
			
			//查询
			$("#btn_query").click(function(e) {
				var table = $('#user_grid_panel').DataTable();
				table.draw(true);
			});
			
			//重置
			$("#btn_reset").click(function(e) {
				$("#id_unbinded").parent().removeClass("checked");
				$("#user_search_form")[0].reset();
			});
			
			//保存
			$("#form_user_save").click(function(e) {
				validator = validateMyForm("user_form");
				if(!validator.form()) {
					return false;
				}
				debugger
				var d = {};
				var loginName = $("#form_user_loginName").val();
				var pass = $("#form_pass").val();
				var isLock="0";
				if($('#form_isLock').parent().hasClass('checked')){
					isLock="1";
				}
				var isShowMessage = "1";
                if($('#form_isShowMessage').parent().hasClass('checked')){
                    isShowMessage = "0";
                }
				var pkId = $("#form_pkId").val();
				var eId = $("#form_eId").val();
				var userClass = $("#form_userClass").val();
				var roleId = $("#form_roleId").val();
				d['loginName'] = loginName;
				d['pass'] = pass;
				d['isLock'] = isLock;
				d['showMessage'] = isShowMessage;
				d['pkId'] = pkId;
				d['userId'] = eId;
				d['userClass'] = userClass;
				d['roleId'] = roleId;
				var table = $('#user_grid_panel').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/sysUser/saveOrUpdateBindUser.mvc",
					"dataType" : "json",
					"data" : d,
					"success" : function(resp) {
						if (resp.msg==true) {
							clearForm();
							rmsBox.notify('success', {msg: '保存成功！'});
							//TODO
							$("#form_btn_close").click();
							$("#tip").modal();
							table.draw(true);
						} else if(resp.msg=='error') {
							rmsBox.notify('error', {msg: '数据异常！',delay:3000});
						} else if(resp.msg=='repeat') {
							rmsBox.notify('error', {msg: '用户名重复！'});
						}
					}
				});
			});
			
			function validateMyForm(formId){
				return $( '#' + formId ).validate({
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	user_loginName:{
			        		'required':true
			        	},
			        	pass:{
			        		'required': true,
			        		'chechPassStds' : true
			        	}
			        	
			        },
			        messages:{
			        	user_loginName:'不能为空',
			        	pass:{
			        		'required': '不能为空',
			        		'chechPassStds' :'密码需在6~14位，以字母开头，不允许使用特殊符号'
			        	}
			        }, 
			        errorPlacement: function (error, element) {
			        	//默认以span形式显示在输入框后
			           error.insertAfter(element);
			           $(element.next()).attr('title', $(error).text()).tooltip();
			           $(error).text('');
			        }
			    });
			};

			function validateAccountForm(formId){
				return $( '#' + formId ).validate({
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	account_login_name:{
			        		'checkLoginName':true
			        	},
			        	account_start_date:{
			        		'checkStartDate':true
			        	}
			        },
			        messages:{
			        	account_login_name:'不能为空',
			        	account_start_date:'不能为空'
			        }, 
			        errorPlacement: function (error, element) {
			        	//默认以span形式显示在输入框后
			           error.insertAfter(element);
			           $(element.next()).attr('title', $(error).text()).tooltip();
			           $(error).text('');
			        }
			    });
			};

			$.validator.addMethod("checkLoginName",function(value,element,params){
				//密码必须以字母开头，6~14位，且不能使用特殊符号
			    var loginName = $("#account_login_name").text();
			    if(loginName == null ||loginName ==''){
			    	return false;
			    }else {
			    	return true;
			    }
			},"");

			$.validator.addMethod("checkStartDate",function(value,element,params){
				//密码必须以字母开头，6~14位，且不能使用特殊符号
				debugger
			    var account_start_date = $("#account_start_date").text();
			    if(account_start_date == null ||account_start_date ==''){
			    	return false;
			    }else {
			    	return true;
			    }
			},"");


			$.validator.addMethod("chechPassStds",function(value,element,params){
				//密码必须以字母开头，6~14位，且不能使用特殊符号
			    var checkpass = /^[a-z,A-Z][a-zA-Z0-9]{5,13}$/;
			    return this.optional(element)||(checkpass.test(value))||value==$("#form_oldPass").val();
			},"");
			
			/**
			 * 清空表单
			 * @returns
			 */
			function clearForm(){
				$("#bind_account input").val('');
				$("#bind_account span.my-text").text('');
				$("#form_isLock").parent().removeClass("checked");
                $("#form_isShowMessage").parent().removeClass("checked");
			};
			
			$(function(){
				util.getDictByParentKey('ZHLXDM', 'id_user_class', '全部');
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
		}
	};
}();
